<template>
  <div class="node">
    <el-row>
      <!-- 头部1 -->
      <el-col :span="24">
        <div>
          <el-card class="node-head-card" shadow="never" :body-style="{padding:  '10px'}">
            <!-- 搜索框和搜索按钮 -->
            <el-row>
              <el-col :span="6">
                <div>
                  <el-input class="node-head-search"
                  clearable placeholder="请输入"
                  v-model="searchInput"></el-input>
                  <el-button style="border-radius:2px;"
                  icon="Search" type="primary" plain @click="getNodes()">搜索</el-button>
                </div>
              </el-col>
              <!-- 刷新按钮 -->
              <el-col :span="2" :offset="16">
                <div>
                  <el-button style="botder-radius:2px" icon="Refresh" plain @click="getNodes()">刷新</el-button>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-col>
      <!-- 数据表格 -->
      <el-col :span="24">
      <div>
        <el-card class="node-body-card" shadow="never" :body-style="{padding: '5px'}">
          <el-table style="width: 100%;font-size:12px;margin-bottom:10px" :data="nodeList">
              <el-table-column width="20"></el-table-column>
              <el-table-column align="left" label="Node名" >
                  <template v-slot="scope" >
                    <a class="node-body-nodename">
                      <div>{{ scope.row.metadata.name}}</div>
                    </a>
                  </template>
              </el-table-column>
              <el-table-column align="center" min-width="100" label="规格">
                <template v-slot="scope">
                  <el-tag type="warning">{{ scope.row.status.capacity.cpu }}C{{ specTrans(scope.row.status.capacity.memory) }}G</el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" min-width="100" label="POD-CIDR">
                <template v-slot="scope">
                  <el-tag type="info">{{ scope.row.spec.podCIDR }} </el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" min-width="100" label="标签">
                <template v-slot="scope">
                  <div v-for="(val,key) in scope.row.metadata.labels" :key="key">
                    <el-popover
                    placement="right"
                    :width="200"
                    trigger="hover"
                    :content="key + ':' + val">
                      <template #reference>
                        <!-- 标签与标签之间间隔设置为5px -->
                        <el-tag style="margin-bottom:3px" type="warning"
                        v-if="key.indexOf('beta') == -1 &&
                        key.indexOf('arch') == -1 && 
                        key.indexOf('kubernetes.io/os') == -1 && 
                        key.indexOf('kubernetes.io/hostname') == -1"
                        >{{ ellipsis(key + ':' + val) }}</el-tag>
                      </template>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>

              <!-- Node节点在线时间 -->
              <el-table-column align=center min-width="100" label="时长(天)">
                  <!-- timeTrans函数用于将格林威治时间转成北京时间 -->
                  <template v-slot="scope">
                      <a class="node-body-daytime">
                        <div>{{ timeTransDay(scope.row.metadata.creationTimestamp) }}</div>
                      </a>
                      <!-- <el-tag type="info">{{ timeTrans(scope.row.metadata.creationTimestamp) }} </el-tag> -->
                  </template>
              </el-table-column>
              <!-- Node节点状态 -->
              <el-table-column align=center min-width="100" label="状态">
                  <template v-slot="scope">
                      <el-tag type="success" v-if="scope.row.status.conditions[4].type == 'Ready' && 
                      scope.row.status.conditions[4].status == 'True'" > Ready </el-tag>
                      <el-tag type="danger" v-if="scope.row.status.conditions[4].type == 'Ready' && 
                      scope.row.status.conditions[4].status == 'Unknown'" > NotReady </el-tag>
                  </template>
              </el-table-column>
              <!-- 操作列，放按钮 -->
              <el-table-column align=center label="操作" width="300">
                  <template v-slot="scope">
                      <el-button size="small" style="border-radius:2px;" icon="Edit" type="primary" plain @click="getNodeDetail(scope)">YAML</el-button>
                      <el-button size="small" style="border-radius:2px;" icon="Delete" type="danger" @click="handleConfirm(scope, '删除', delNode)">删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
          <!-- size-change 单页大小改变后触发
          current-change 页数改变后触发
          current-page 当前页，跟后端page一致
          page-size 单页大小，跟后端limit一致 -->
          <el-pagination
            class="node-body-pagination"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="pagesizeList"
            :page-size="pagesize"
            layout="total,sizes,prev,pager,next,jumper"
            :total="nodeTotal"></el-pagination>
        </el-card>
      </div>

      </el-col>
    </el-row>
    <el-dialog title="YAML信息" v-model="yamlDialog" width="60%" top="5%">
        <codemirror
            :value="contentYaml"
            border
            :options="cmOptions"
            height="500"
            style="font-size:14px;"
            @change="onChange"
        ></codemirror>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="yamlDialog = false">取 消</el-button>
                <!-- <el-button type="primary" @click="updateNode()">更 新</el-button> -->
            </span>
        </template>
    </el-dialog>
  </div>
  
</template>

<script>
import common from "../common/Config";
import httpClient from "../../utils/request";
import yaml2obj from 'js-yaml';
import json2yaml from "json2yaml";

export default {
  data() {
    return {
      // 主要配置
      defaultOpts: {
       // 编辑器的值
        value: '',
         // 编辑器主题：vs, hc-black, or vs-dark，更多选择详见官网
        theme: 'vs-dark',
        // 右侧不显示编辑器预览框
        roundedSelection: true, 
        // 自动缩进
        autoIndent: true ,
        // 是否只读
        readOnly: false, 
        // 语言类型java,c,php更多选择详见官网
        language: 'yaml', 
      },
        // 编辑器对象
      monacoEditor: {},

      //搜索
      searchInput: '',
      // 命名空间属性
      namespaceValue: 'default',
      namespaceList:  [],
      namespaceListUrl: common.k8sNamespaceList,
      // 创建
      createNodeDrawer: false,
      fullscreenLoading: false,
      direction: 'rtl',
      // 列表
      apploading: false,
      nodeList: [],
      nodeTotal: 0,
      getNodeData: {
          url: common.k8sNodeList,
          params: {
            filtername: '',
            page: 1,
            limit: 10
          }
      },
      //分页
      currentPage: 1,
      pagesize: 10,
      pagesizeList: [10,20,30],
      // 编辑器配置
      cmOptions: common.cmOptions,
      contentYaml: '',

      // 详 情
      yamlDialog: false,
      nodeDetail: {},
      getnodeDetailData: {
        url: common.k8sNodeDetail,
        params: {
          nodename: '',
        }
      }, 
    }
  },
  methods: {

    getNodepods(){
      //跳转至/login页面
      this.$router.push('/workload/pod');
    },
    
    //json to yaml 
    transYaml(content) {
      return json2yaml.stringify(content)
    },
    transObj(content) {
      return yaml2obj.load(content)
    },
    // 编辑器内容发生变化时触发的方法
    onChange(val) {
      this.contentYaml = val
    },
    //分页
    handleSizeChange(size) {
      this.pagesize = size
      this.getNodes()
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getNodes()
    },
    //格林威治时间转为北京时间
    // timeTrans(timestamp) {
    //     let date = new Date(new Date(timestamp).getTime() + 8 * 3600 * 1000)
    //     console.log(date)
    //     date = date.toJSON();
    //     date = date.substring(0, 19).replace('T', ' ')
    //     return date 
    // },
    timeTransDay(timestamp) {
        var nowdate = new Date();
        let createdate = new Date(new Date(timestamp).getTime())
        // getTime()是获取时间戳,精度ms
        // 计算时间戳之差,根据时间戳计算之差算出来天数
        var surplusdate = nowdate.getTime() - createdate.getTime()
        // 计算天数
        var daydouble = surplusdate / (24 * 60 * 60 * 1000);
        // 向上取整
        var day = Math.ceil(daydouble);
        return day 
    },
    specTrans(str) {
        if ( str.indexOf('Ki') == -1 ) {
            return str
        }
        let num = str.slice(0,-2) / 1024 / 1024
        return num.toFixed(0)
    },
    //字符串的截取
    ellipsis(value) {
      // return value.length>15?value.substring(0,15)+'...':value
      // return value.replace(/node-role.kubernetes.io\/master/g,'master').replace(/:/g,'')
      return value.replace(/node-role.kubernetes.io\//,'').replace(/:$/,'')
    },
    
    // 获取node 列表
    getNodes(){
      this.apploading = true
      this.getNodeData.params.filtername = this.searchInput
      this.getNodeData.params.page = this.currentPage
      this.getNodeData.params.limit = this.pagesize
      httpClient.get(this.getNodeData.url,{params: this.getNodeData.params})
      .then(res => {
        this.nodeList = res.data.items
        this.nodeTotal = res.data.total
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
      this.apploading = false
    },
    // 获取详情, e参数标识传入的scope插槽，.row是该行的数据
    getNodeDetail(e) {
      this.getnodeDetailData.params.nodename = e.row.metadata.name
      httpClient.get(this.getnodeDetailData.url,{params: this.getnodeDetailData.params})
      
      .then(res => {
        this.nodeDetail = res.data
        this.contentYaml = this.transYaml(this.nodeDetail)
        this.yamlDialog = true
      })
      .catch(res => {
        this.$message.error({
          message: res.msg
        })
      })
    },
  },
  beforeMount(){
    this.getNodes()
  }
}

</script>

<style scoped>
  .node-head-card, .node-body-card {
    border-radius: 1px;
    margin-bottom: 5px;
  }
  .node-head-search {
    width: 160px;
    margin-right: 10px;
  }
  /* 数据表格node名颜色 */
  .node-body-nodename {
    color: #4795EE;
  }
  .node-body-daytime {
    color: #3046b3;
  }
  /* node名鼠标悬停 */
  .node-body-nodename:hover {
    color: rgb(84, 138,238);
    cursor: pointer;
    font-weight: bold;
  }

</style>